import glob
import os
import tkinter as tk 
from tkinter import messagebox
from PIL import Image, ImageTk, ImageDraw,ImageFilter
import math
import cv2
from PIL import Image, ImageFilter, ImageEnhance
import numpy as np

def create_window(parent=None):

    # 创建窗口
    if parent is None:
        root = tk.Tk()
    else:
        root = tk.Toplevel(parent)

    root.title("图片缩放工具，原尺寸")
    root.config(bg="grey")
    root.geometry("1000x1000+0+0")

    # background_image = Image.open("D:/Users/admin/Downloads/composite/body_output/50001_ATTACK_0/0.png")
    # background_photo = ImageTk.PhotoImage(background_image)
    # canvas.
    # 暂停修改--将index保持不动，一直重复刷同一帧

    global offX, offY,center_x,center_y,canvas_width,canvas_height
    offX = 60
    offY = 50
    center_x = 0
    center_y = 0
    canvas_width = 750
    canvas_height = 800
    center_x = canvas_width / 2
    center_y = canvas_height / 2

    global imgs_scale, scale_value, scale_index
    scale_value = 1
    imgs_scale = []
    scale_index = 0

    # 缩放图片路径输入框
    entry_scale_change_path = tk.StringVar()
    entry_path = tk.Entry(root, textvariable=entry_scale_change_path)
    entry_path.place(x=offX, y=offY - 40)

    # 图像绘制位置坐标
    canvas_scale = tk.Canvas(root, width=800, height=800, bg="gray")
    canvas_scale.place(x=offX, y=offY + 100)

    check_var = tk.IntVar()
    tk.Label(root, text="勾选显示十字线", bg='green').place(x=offX + 300, y=offY - 3)
    tk.Checkbutton(root, variable=check_var).place(x=offX + 400, y=offY - 6)

    check_var1 = tk.IntVar()
    tk.Label(root, text="勾选加载当前目录", bg='green').place(x=offX + 300, y=offY - 37)
    tk.Checkbutton(root, variable=check_var1).place(x=offX + 400, y=offY - 40)

    def check_status():
        if check_var.get():
            return 'on'
        else:
            return 'off'
    def check_status1():
        if check_var1.get():
            return 'on'
        else:
            return 'off'
    # 使用open CV的图像算法处理过后的图片并保存下来
    def HandleImg(input_image_path, output_image_path, scale_factor):
        # 检查文件是否存在
        if not os.path.exists(input_image_path):
            print(f"文件不存在：{input_image_path}")
        else:
            # 尝试读取图像
            with open(input_image_path, 'rb') as f:
                img_data = np.frombuffer(f.read(), dtype=np.uint8)
            # image = cv2.imread(input_image_path, cv2.IMREAD_UNCHANGED)  # 保留透明度通道
            image = cv2.imdecode(img_data, cv2.IMREAD_UNCHANGED)
            if image is None:
                print(f"无法读取图像：{input_image_path}")
            else:
                print("图像读取成功！")

        # 判断图像是否有Alpha通道
        if image.shape[2] == 4:  # 图像是RGBA格式，包含透明度通道
            bgr_image = image[:, :, :3]  # 只取BGR部分（不包括Alpha通道）
            alpha_channel = image[:, :, 3]  # 获取Alpha通道
        else:
            bgr_image = image
            alpha_channel = None

        # 将图像从 BGR 格式转换为 RGB 格式（因为 OpenCV 使用 BGR，而 PIL 使用 RGB）
        rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)

        # 使用 OpenCV 的 INTER_CUBIC 插值方法进行放大
        enlarged_image = cv2.resize(rgb_image, (0, 0), fx=scale_factor, fy=scale_factor, interpolation=cv2.INTER_CUBIC)

        if alpha_channel is not None:
            # 对于带有透明度的图像，放大Alpha通道
            enlarged_alpha = cv2.resize(alpha_channel, (0, 0), fx=scale_factor, fy=scale_factor,
                                        interpolation=cv2.INTER_CUBIC)
            # 合并RGB和Alpha通道
            enlarged_image = np.dstack((enlarged_image, enlarged_alpha))

        # 使用 PIL 进一步处理图像
        pil_image = Image.fromarray(enlarged_image)
        original_pil = Image.fromarray(bgr_image)

        # 计算居中位置
        bg_width, bg_height = original_pil.size
        fg_width, fg_height = pil_image.size
        background = Image.new('RGBA',(bg_width,bg_height), (255, 255, 255, 0))
        bg_width, bg_height=background.size
        x = (bg_width - fg_width) // 2
        y = (bg_height - fg_height) // 2

        # 粘贴图像
        background.paste(pil_image, (x, y))


        # 保存放大后的图像
        background.save(output_image_path,'PNG')
        if background is not None:
            background.close()
            print(u'图片关闭')
        print(f"图像处理成功")

    # 播放算法缩放过后的图片
    def PlayReSizeImage(input_image_path, scale_factor):
        # 尝试读取图像
        with open(input_image_path, 'rb') as f:
            img_data = np.frombuffer(f.read(), dtype=np.uint8)
        #image = cv2.imread(input_image_path, cv2.IMREAD_UNCHANGED)  # 保留透明度通道
        image = cv2.imdecode(img_data, cv2.IMREAD_UNCHANGED)
        if image is None:
            print(f"无法读取图像：{input_image_path}")

        # 判断图像是否有Alpha通道
        if image.shape[2] == 4:  # 图像是RGBA格式，包含透明度通道
            bgr_image = image[:, :, :3]  # 只取BGR部分（不包括Alpha通道）
            alpha_channel = image[:, :, 3]  # 获取Alpha通道
        else:
            bgr_image = image
            alpha_channel = None

        # 将图像从 BGR 格式转换为 RGB 格式（因为 OpenCV 使用 BGR，而 PIL 使用 RGB）
        rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)

        # 使用 OpenCV 的 INTER_CUBIC 插值方法进行放大
        enlarged_image = cv2.resize(rgb_image, (0, 0), fx=scale_factor, fy=scale_factor, interpolation=cv2.INTER_CUBIC)

        if alpha_channel is not None:
            # 对于带有透明度的图像，放大Alpha通道
            enlarged_alpha = cv2.resize(alpha_channel, (0, 0), fx=scale_factor, fy=scale_factor,
                                        interpolation=cv2.INTER_CUBIC)
            # 合并RGB和Alpha通道
            enlarged_image = np.dstack((enlarged_image, enlarged_alpha))

        # 使用 PIL 进一步处理图像
        pil_image = Image.fromarray(enlarged_image)
        return pil_image

    # 循环处理当前文件夹下的所有图片的缩放
    def enlarge_image_like_photoshop():
        input_folder = entry_scale_change_path.get()
        output_folder = os.path.dirname(input_folder) + "\\scale_output"  # r"D:\Users\admin\Desktop\File\130001\output"
        if not os.path.exists(output_folder):
            os.makedirs(output_folder)
        if check_status1() == 'on':
            for item in os.listdir(input_folder):
                if item.endswith('.png') or item.endswith('.jpg'):
                    item_path = os.path.join(input_folder, item)
                    save_photoshop(None, input_folder, output_folder, item_path, item)
        else:
            for root, dirs, files in os.walk(input_folder):
                for filename in files:
                    if filename.endswith('.png') or filename.endswith('.jpg'):
                        input_path = os.path.join(root, filename)
                        save_photoshop(root, input_folder, output_folder, input_path, filename)


        print(f"当前文件夹下的所有图像全部处理成功")

    def save_photoshop(root,input_folder,output_folder,input_path,filename):
        if root is None:
            output_subfolder = os.path.join(output_folder)
        else:
            relative_path = os.path.relpath(root, input_folder)
            output_subfolder = os.path.join(output_folder, relative_path)

        # 确保输出子文件夹存在
        if not os.path.exists(output_subfolder):
            os.makedirs(output_subfolder)

        output_path = os.path.join(output_subfolder, filename)
        HandleImg(input_path, output_path, scale_value)
    # 加载
    def load_images():
        global imgs_scale, button_scale,scale_index
        global button_scale_load, button_scale_sure, scale_value, input_folder, output_folder, imgs_scale_path
        scale_index=0
        imgs_scale_path = []
        input_folder = entry_scale_change_path.get()
        if check_status1() == 'on':
            if not os.path.exists(input_folder):
                print("目录不存在!")
            else:
                # 遍历目录
                for item in os.listdir(input_folder):
                    if item.endswith('.png') or item.endswith('.jpg'):
                        item_path = os.path.join(input_folder, item)
                        imgs_scale_path.append(item_path)
        else:
            print(entry_scale_change_path.get())
            print(input_folder)
            for root, dirs, files in os.walk(input_folder):
                for filename in files:
                    if filename.endswith('.png') or filename.endswith('.jpg'):
                        img_path = os.path.join(root, filename)
                        imgs_scale_path.append(img_path)


        imgs_scale = [Image.open(path) for path in imgs_scale_path]
        update_frame_sclae()

    # 缩放量输入框
    entry_scale_change = tk.StringVar()
    entry_path = tk.Entry(root, textvariable=entry_scale_change, width=5)
    entry_path.place(x=offX, y=offY - 3)

    # 获取输入的缩放值
    def get_scale_value():
        global scale_value
        scale_value = 0
        scale_value = float(entry_scale_change.get())
        update_frame_sclae()

    button_scale_load = tk.Button(root, text="缩放图片", command=enlarge_image_like_photoshop).place(x=offX + 200,
                                                                                                     y=offY - 6)
    button_scale_sure = tk.Button(root, text="预览", command=get_scale_value).place(x=offX + 100, y=offY - 6)
    button_scale = tk.Button(root, text="加载图片", command=load_images).place(x=offX + 200, y=offY - 40)

    # 图片播放
    def update_frame_sclae():
        global imgs_scale, scale_index, photo, resized_img, name, root_after2
        length = len(imgs_scale)
        if imgs_scale:
            canvas_scale.delete("all")
            #length = len(imgs_scale)
            if  length==1:
                img_scale = imgs_scale[0]
            else:
                img_scale = imgs_scale[scale_index]
            resized_img = PlayReSizeImage(img_scale.filename, scale_value)
            # name = img_scale.filename.split("\\")[len(img_scale.filename.split("\\")) - 1]
            # resize = [math.ceil(img_scale.size[0]*scale_value), math.ceil(img_scale.size[1]*scale_value)]
            # resized_img = img_scale.resize(resize, Image.Resampling.LANCZOS)
            photo = ImageTk.PhotoImage(resized_img)
            org_photo = ImageTk.PhotoImage(img_scale)
            x = int(photo.width() / 2)
            y = int(photo.height() / 2)

            canvas_scale.create_rectangle(center_x - org_photo.width() / 2, center_y - org_photo.height() / 2, center_x + org_photo.width() / 2,
                                          center_y + org_photo.height() / 2, fill="white", outline="black")
            canvas_scale.create_image(center_x, center_y, anchor=tk.CENTER, image=photo)
            if check_status() == 'on':
                canvas_scale.create_line(0, center_y, canvas_width, center_y, fill="red", width=1)
                canvas_scale.create_line(center_x, 0, center_x, canvas_height, fill="red", width=1)

            scale_index = (scale_index + 1) % length  # 循环显示
        if length != 1:
            root_after2 = root.after(200, update_frame_sclae)
    #update_frame_sclae()
    if parent is None:
        root.mainloop()
if __name__ == "__main__":
    create_window()
#root.mainloop()